package com.qiantu.phone.ui.fragment.device;

import android.view.View;
import android.widget.TextView;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControlDataFreshAirBean;
import com.qiantu.api.entity.DeviceModeValue;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.DeviceInfoParseUtil;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.adapter.DeviceModeValueAdapter;
import com.qiantu.phone.ui.uiutil.DeviceType;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.FreshAirSwitchView;
import com.qiantu.phone.widget.WindSpeedSeekBar;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * desc   : 地暖设备
 */
public final class FreshAirFragment extends BaseDeviceFragment {

    private TextView tvFreshAir;
    private TextView tvExhaustWind;
    private FreshAirSwitchView freshAirSwitchView;
    private WindSpeedSeekBar windSpeedSeekBar;
    private View windSpeedSeekBarContainer;
    private WindSpeedSeekBar exhaustWindSpeedSeekBar;
    private RecyclerView modeValueRecyclerView;
    private DeviceModeValueAdapter mDeviceModeValueAdapter;
    private ControlDataFreshAirBean controlDataInfoBean;
    private ControlDataFreshAirBean.ControlData controlData;

    public static FreshAirFragment newInstance() {
        FreshAirFragment fragment = new FreshAirFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_fresh_air;
    }

    @Override
    protected void initView() {
        super.initView();
        tvFreshAir = findViewById(R.id.tv_fresh_air);
        tvExhaustWind = findViewById(R.id.tv_exhaust_wind);
        freshAirSwitchView = findViewById(R.id.fresh_air_switch_view);
        windSpeedSeekBarContainer = findViewById(R.id.wind_speed_seek_bar_container);
        windSpeedSeekBar = findViewById(R.id.wind_speed_seek_bar);
        exhaustWindSpeedSeekBar = findViewById(R.id.exhaust_wind_speed_seek_bar);
        modeValueRecyclerView = findViewById(R.id.mode_value_recycler_view);
        controlDataInfoBean = DeviceInfoParseUtil.parseData(getContext(), mDevice.getDeviceType(), ControlDataFreshAirBean.class);
        controlData = controlDataInfoBean.getControlData();
        freshAirSwitchView.setOnChangeListener(new FreshAirSwitchView.OnChangeListener() {
            @Override
            public void onSwitch(boolean isOpen) {
//                setStatusBySwitch(isOpen);
                freshAirSwitchView.setOpenState(!isOpen);
                switchOperation();
            }
        });
        windSpeedSeekBar.setOnSeekBarChangeListener(new WindSpeedSeekBar.OnSeekBarChangeListener() {
            @Override
            public void onValueChanged(int step) {
                if(controlData.getWindspeed() != null && step < controlData.getWindspeed().size()){
                    int resId = getResources().getIdentifier(controlData.getWindspeed().get(step).getName(), "string", getContext().getPackageName());
                    freshAirSwitchView.setSpeedName(getString(resId));
                    windSpeedOperation(controlData.getWindspeed().get(step).getValue(), false);
                }
            }
        });
        exhaustWindSpeedSeekBar.setOnSeekBarChangeListener(new WindSpeedSeekBar.OnSeekBarChangeListener() {
            @Override
            public void onValueChanged(int step) {
                if(controlData.getWindspeed() != null && step < controlData.getExhaustspeed().size()){
                    windSpeedOperation(controlData.getExhaustspeed().get(step).getValue(), true);
                }
            }
        });
        mDeviceModeValueAdapter = new DeviceModeValueAdapter(getContext());
        mDeviceModeValueAdapter.setData(controlData.getMode());
        mDeviceModeValueAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                if(!freshAirSwitchView.isOpen()){
                    ToastUtils.show(R.string.device_off_disable);
                    return;
                }
                mDeviceModeValueAdapter.selectItem(position);
                DeviceModeValue valueBean = mDeviceModeValueAdapter.getData().get(position);
                modeOperation(valueBean.getValue());
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        modeValueRecyclerView.setLayoutManager(linearLayoutManager);
        modeValueRecyclerView.setAdapter(mDeviceModeValueAdapter);
        updateView();
    }

    private void switchOperation() {
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.POWER, freshAirSwitchView.isOpen() ? 0 : 1);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setIsOpen(!freshAirSwitchView.isOpen());
                setStatusBySwitch(mDevice.getIsOpen());
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void modeOperation(int mode) {
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.MODE, mode);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setMode(mode);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void windSpeedOperation(int windspeed, boolean isExhaustspeed) {
        Map<String, Object> option = new HashMap<>();
        if(isExhaustspeed){
            option.put(LLDeviceUtil.EXHAUST_SPEED, windspeed);
        }else{
            option.put(LLDeviceUtil.WIND_SPEED, windspeed);
        }
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                if(isExhaustspeed){
                    mDevice.setExhaustSpeed(windspeed);
                }else{
                    mDevice.setWindSpeed(windspeed);
                }
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void selectValue(Integer value){
        //设备关闭不设置设置缓存里的模式
        if(!freshAirSwitchView.isOpen() || mDeviceModeValueAdapter.getData() == null){
            return;
        }
        for(int i=0; i<mDeviceModeValueAdapter.getData().size(); i++){
            if(mDeviceModeValueAdapter.getData().get(i).getValue() == value){
                mDeviceModeValueAdapter.selectItem(i);
                break;
            }
        }
    }

    private void setStatusBySwitch(boolean isOpen){
        freshAirSwitchView.setOpenState(isOpen);
        windSpeedSeekBar.setOpenState(isOpen);
        exhaustWindSpeedSeekBar.setOpenState(isOpen);
        if(isOpen){
            selectValue(mDevice.getMode());
        }else{
            mDeviceModeValueAdapter.clearSelected();
        }
    }

    protected void updateView() {
        super.updateView();
//        if (mDevice.isIsOnline()) {
            freshAirSwitchView.setEnabled(true);
            if(DeviceType.LANSHE_FRESHAIR.stringType.equals(mDevice.getDeviceType())){
                freshAirSwitchView.setHasValue(true);
                freshAirSwitchView.setValue(mDevice.getAmbienttemperature() + "°C");
            }else{
                freshAirSwitchView.setHasValue(false);
            }
            freshAirSwitchView.setSpeedName(getWindSpeedName(mDevice.getWindSpeed(), false));
            setStatusBySwitch(mDevice.getIsOpen());
//        } else {
//            freshAirSwitchView.setEnabled(false);
//            setStatusBySwitch(false);
//        }
        if(controlData != null && controlData.getWindspeed() != null && controlData.getWindspeed().size() > 0){
            windSpeedSeekBar.setVisibility(View.VISIBLE);
            windSpeedSeekBar.setStep(getWindSpeedStep(mDevice.getWindSpeed(), false));
            windSpeedSeekBar.setWindSpeedTotalStep(controlData.getWindspeed().size());
        }else{
            tvFreshAir.setVisibility(View.GONE);
            windSpeedSeekBar.setVisibility(View.GONE);
        }
        //排风风速
        if(controlData != null && controlData.getExhaustspeed() != null && controlData.getExhaustspeed().size() > 0){
            tvFreshAir.setVisibility(View.VISIBLE);
            windSpeedSeekBar.setLineHeight(getResources().getDimensionPixelSize(R.dimen.dp_6));
            windSpeedSeekBar.setWindSpeedBarHeight(getResources().getDimensionPixelSize(R.dimen.dp_22));
            windSpeedSeekBar.setWindSpeedBarThumbHeight(getResources().getDimensionPixelSize(R.dimen.dp_36));
            windSpeedSeekBar.setWindSpeedBarOpenCloseThumb(R.attr.icon_devicecontrol_freshair_exhaustair, R.attr.icon_devicecontrol_freshair_exhaustair_close);
            windSpeedSeekBarContainer.setPadding(windSpeedSeekBarContainer.getPaddingLeft(), windSpeedSeekBarContainer.getPaddingTop(), windSpeedSeekBarContainer.getPaddingRight(), getResources().getDimensionPixelSize(R.dimen.dp_8));
            tvExhaustWind.setVisibility(View.VISIBLE);
            exhaustWindSpeedSeekBar.setVisibility(View.VISIBLE);
            exhaustWindSpeedSeekBar.setStep(getWindSpeedStep(mDevice.getExhaustSpeed(), true));
            exhaustWindSpeedSeekBar.setWindSpeedTotalStep(controlData.getExhaustspeed().size());
        }else{
            tvFreshAir.setVisibility(View.GONE);
            windSpeedSeekBar.setLineHeight(getResources().getDimensionPixelSize(R.dimen.dp_7));
            windSpeedSeekBar.setWindSpeedBarHeight(getResources().getDimensionPixelSize(R.dimen.dp_40));
            windSpeedSeekBar.setWindSpeedBarThumbHeight(getResources().getDimensionPixelSize(R.dimen.dp_40));
            if(mDeviceModeValueAdapter.getItemCount() > 0){
                windSpeedSeekBarContainer.setPadding(windSpeedSeekBarContainer.getPaddingLeft(), windSpeedSeekBarContainer.getPaddingTop(), windSpeedSeekBarContainer.getPaddingRight(), getResources().getDimensionPixelSize(R.dimen.dp_18));
            }else{
                windSpeedSeekBarContainer.setPadding(windSpeedSeekBarContainer.getPaddingLeft(), windSpeedSeekBarContainer.getPaddingTop(), windSpeedSeekBarContainer.getPaddingRight(), getResources().getDimensionPixelSize(R.dimen.dp_48));
            }
            tvExhaustWind.setVisibility(View.GONE);
            exhaustWindSpeedSeekBar.setVisibility(View.GONE);
        }
    }

    private String getWindSpeedName(Integer value, boolean isExhaust){
        if(value == null){
            return null;
        }
        List<DeviceModeValue> deviceModeValues;
        if(isExhaust){
            deviceModeValues = controlData.getExhaustspeed();
        }else{
            deviceModeValues = controlData.getWindspeed();
        }
        if(deviceModeValues == null || deviceModeValues.size() == 0){
            return null;
        }
        for(int i=0; i<deviceModeValues.size(); i++){
            if(deviceModeValues.get(i).getValue() == value){
                int resId = getResources().getIdentifier(deviceModeValues.get(i).getName(), "string", getContext().getPackageName());
                return getResources().getString(resId);
            }
        }
        //设备控制页没有未设置，默认返回第一个
        int resId = getResources().getIdentifier(deviceModeValues.get(0).getName(), "string", getContext().getPackageName());
        return getResources().getString(resId);
    }

    private int getWindSpeedStep(Integer value, boolean isExhaust){
        if(value == null){
            return 0;
        }
        List<DeviceModeValue> deviceModeValues;
        if(isExhaust){
            deviceModeValues = controlData.getExhaustspeed();
        }else{
            deviceModeValues = controlData.getWindspeed();
        }
        if(deviceModeValues == null || deviceModeValues.size() == 0){
            return 0;
        }
        for(int i=0; i<deviceModeValues.size(); i++){
            if(deviceModeValues.get(i).getValue() == value){
                return i;
            }
        }
        return 0;
    }

    private String getWindSpeedValue(Integer step, boolean isExhaust){
        if(step == null){
            return null;
        }
        List<DeviceModeValue> deviceModeValues;
        if(isExhaust){
            deviceModeValues = controlData.getExhaustspeed();
        }else{
            deviceModeValues = controlData.getWindspeed();
        }
        for(int i=0; i<deviceModeValues.size(); i++){
            if(i == step){
                return deviceModeValues.get(i).getValue() + "";
            }
        }
        return null;
    }
}